#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/S3'
require 'basic_configuration'
require 'aws_context'
require 'pp'

#  Retrieves the signed uri to share an S3 object.
# The bucket may be supplied on the command line or in the environment.

if ARGV[0] == '-?' || ARGV.size < 2 then
  puts "usage: get-signed-uri key hours_until_expiry [bucket]"
  exit 1
end
key=ARGV[0]
hours_until_expiry=ARGV[1].to_f
if ARGV.size >= 3
  bucket = ARGV[2]
end

config = BasicConfiguration.new
bucket = config.aws[:aws_bucket] unless bucket
if bucket.nil?
  puts "AWS_BUCKET environment variable must be set or defined in config file."
  exit 1
end

Signal.trap("INT") do
  exit 2
end

s3 = AwsContext.instance.s3(*config.keys)
begin
  expiry_time = Time.now.to_i + (hours_until_expiry * 3600).to_i
  puts s3.sign_uri('GET', expiry_time, bucket, key)
rescue
  puts "error: #{$!} -- not generated"
  exit 1
end

